package org.example;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

public class Server {
    private static final Logger LOGGER = Logger.getLogger(Server.class);

    private static final Certificate certificate;
    private static final KeyPair KEY_PAIR;
    private static final Map<Client, Key> KEY_MAP = new HashMap<>();

    static {
        // 生成密钥对，并向CA申请证书
        KEY_PAIR = SecretKeyUtil.createRSAKey();
        certificate = applyCertificate();
    }

    public Certificate getCertificate() {
        return certificate;
    }

    public void registerSecretKey(Client client, byte[] secretKey) {
        KEY_MAP.put(client, decryptSecretKey(secretKey));
    }

    /**
     * 申请证书
     */
    private static Certificate applyCertificate() {
        String organization = "mar";
        String domainName = "www.example.org";
        return CA.issueCertificate(organization, domainName, KEY_PAIR.getPublic());
    }

    public byte[] response(Client client, byte[] msg) {
        // 获取传输数据使用的对称密钥
        Key secretKey = KEY_MAP.get(client);
        // 解密msg
        byte[] decryptRequestData = SecretKeyUtil.decryptDES(secretKey, msg);
        String requestData = new String(decryptRequestData, StandardCharsets.UTF_8);
        LOGGER.info(String.format("接受到请求数据内容为[%s]", requestData));
        // 响应的数据内容
        String responseData = requestData + "_response";
        LOGGER.info(String.format("响应数据内容为[%s]", responseData));
        // 加密response
        return SecretKeyUtil.encryptDES(secretKey, responseData.getBytes(StandardCharsets.UTF_8));
    }

    private Key decryptSecretKey(byte[] secretKey) {
        byte[] decryptSecretKey = SecretKeyUtil.decryptRSA(KEY_PAIR.getPrivate(), secretKey);
        return SecretKeyUtil.generateDESKey(decryptSecretKey);
    }

}
